const Router = require('koa-router');
const router = new Router();
const api = require('../api');

const formatDate = require('../middleware/formatDate');
const checkToken = require('../middleware/checkToken');
var mqtt = require('mqtt');
var username = 'admin'; 
var password = '123456'; 
var hostname = 'localhost:61613'; 
var sub = '/public/control';
var topic = '/public/sensor';
var url = 'mqtt://' + username + ':' + password + '@' + hostname;
var data = {}
var client = mqtt.connect(url);//连接到服务端
client.subscribe(topic);
client.on('message',function(topic,message){
  data = message.toString()
  var d = eval("(" + data + ")");
  if(d.type==='sensor'){
    let sensor = {
      datat : d.datat,
      datah : d.datah,
      createTime : formatDate()
   }
    api.createSensorData(sensor)
  }
  console.log(topic,message)
})

function sendMsg(qtt){
  client.publish(sub,JSON.stringify(qtt),{qos:1, retain: true});
}

router
.use(['/control','/remove','/lists'],checkToken())
// 创建分类 checkToken,
.post('/control', async(ctx,next)=>{
  //await checkToken(ctx,next);
  
  var cino = ctx.request.body.cino
  var cstate = ctx.request.body.cstate
  //这里控制
  var qtt = {}
  qtt.ino = cino 
  qtt.state = cstate?1:0
  try{
    sendMsg(qtt)
    ctx.body = {
      code:200,
      message:'操作成功'
    };
  }catch(err){
    ctx.body = {
      code:401,
      message:'操作失败'
    };
  }
  
})

// 删除所有传感器数据
.post('/remove', async(ctx,next)=>{
  //await checkToken(ctx,next);
  await api.removeAllSensorData()
  .then(()=>{
    ctx.body = {
      code:200,
      message:'清除成功'
    };
  }).catch(err=>{
    res.body = {
      code:-200,
      message:err.toString()
    };
  });
})
// 获取所有分类 checkToken,
.get('/lists', async(ctx,next)=>{
  //await checkToken(ctx,next);
  await api.findAllSensorData()
  .then((lists)=>{
    var datats = []
    var datahs = []
    var createTimes = []
    lists.map(item=>{
      datats.push(item.datat)
      datahs.push(item.datah)
      createTimes.push(item.createTimes)
    })   
    ctx.body = {
      code:200,
      data:{
        datats,
        datahs,
        createTimes
      }
    };
  }).catch(err=>{
    res.body = {
      code:-200,
      message:err.toString()
    };
  });
})
// 无权限获取分类给前台使用
.get('/noAuth', async(ctx,next)=>{
  await api.findAllSensorData()
  .then((lists)=>{
    var datats = []
    var datahs = []
    var createTimes = []
    lists.map(item=>{
      datats.push(parseInt(item.datat))
      datahs.push(parseInt(item.datah))
      createTimes.push(item.createTime)
    })   
    ctx.body = {
      code:200,
      data:{
        datats,
        datahs,
        createTimes
      }
    };
  }).catch(err=>{
    res.body = {
      code:-200,
      message:err.toString()
    };
  });
});

module.exports = router;
